#!/usr/bin/python
import psycopg2
import configparser
import os

def getConfig(section, key):
    try:
        config = configparser.ConfigParser()
        path = os.path.split(os.path.realpath(__file__))[0] + '/value.conf'
        config.read(path)
        return config.get(section, key)
    except configparser.NoOptionError:
        print("配置文件中不存在key为{key}的值".format(key=key))
        return None

def __execute(sql):
    database = getConfig("postgresql", "database")
    user = getConfig("postgresql", "user")
    password = getConfig("postgresql", "password")
    host = getConfig("postgresql", "host")
    port = getConfig("postgresql", "port")
    conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
    print("Opened database successfully")

    cur = conn.cursor()
    cur.execute(sql)
    # cur.execute('''CREATE TABLE COMPANY
    #        (ID INT PRIMARY KEY     NOT NULL,
    #        NAME           TEXT    NOT NULL,
    #        AGE            INT     NOT NULL,
    #        ADDRESS        CHAR(50),
    #        SALARY         REAL);''')
    print("Table created successfully")

    conn.commit()
    conn.close()


# def __execute_sql(sql="show server_version"):
def __execute_sql(sql):
    database = getConfig("postgresql", "database")
    user = getConfig("postgresql", "user")
    password = getConfig("postgresql", "password")
    host = getConfig("postgresql", "host")
    port = getConfig("postgresql", "port")
    conn = psycopg2.connect(database=database, user=user, password=password, host=host, port=port)
    print("Opened database successfully")
    cur = conn.cursor()
    cur.execute(sql)
    # print("Table created successfully")
    # conn.commit
    # conn.close()
    # return "success"
    # cur = conn.cursor()
    # cur.execute(sql)
    # cur.execute('''CREATE TABLE COMPANY
    #        (ID INT PRIMARY KEY     NOT NULL,
    #        NAME           TEXT    NOT NULL,
    #        AGE            INT     NOT NULL,
    #        ADDRESS        CHAR(50),
    #        SALARY         REAL);''')
    print("Table created successfully")

    conn.commit()
    conn.close()

if __name__ == '__main__':
    sql = '''create table test(
    gid int4 NOT NULL,
    id int4,
    NAME varchar(50),
    geom geometry,
    CONSTRAINT test_pkey PRIMARY KEY (gid));'''
    # __execute(sql);
    __execute_sql(sql)